﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using VoL.Domain.Common.DTO;
using VoL.Domain.Infrastructure;
using VoL.Domain.IServices.EquipmentManage;
using VOL.Entity.DomainModels;
using VOL.WebApi.Common;

namespace VoL.Domain.Services.EquipmentManage
{
    /// <summary>
    /// 设备记录服务类
    /// </summary>
    public partial class EquipmentRecordServices : IEquipmentRecordServices
    {
        /// <summary>
        /// 设备记录仓储接口
        /// </summary>
        private readonly IBaseRepository<EquipmentRecord> _equipmentRecordRepository;
        /// <summary>
        /// 设备记录服务类构造函数
        /// </summary>
        /// <param name="equipmentRecordRepository">设备记录仓储接口</param>
        public EquipmentRecordServices(IBaseRepository<EquipmentRecord> equipmentRecordRepository)
        {
            _equipmentRecordRepository = equipmentRecordRepository;
        }

        /// <summary>
        /// 创建或更新设备借还记录
        /// </summary>
        /// <param name="equipmentRecordDto">设备借还记录表</param>
        /// <returns></returns>
        public async Task<APIResult<object>> CUEquipmentRecord(EquipmentRecordDTO equipmentRecordDto)
        {
            APIResult<object> res = new APIResult<object>()
            {
                Message = APIEnum.创建成功.ToString(),
                Code = APIEnum.创建成功,
                Data = 1
            };
            int i = 0;
            try
            {
                if (equipmentRecordDto.Id == 0 || equipmentRecordDto.Id == null)
                {
                    var newEquipmentRecord = new EquipmentRecord
                    {
                        EquipmentType = equipmentRecordDto.EquipmentType,
                        EquipmentNo = equipmentRecordDto.EquipmentNo,
                        Borrower = equipmentRecordDto.Borrower,
                        borrowDate = DateTime.Now,
                        CurrentUser = equipmentRecordDto.CurrentUser,
                        ReturnUser = equipmentRecordDto.ReturnUser,
                        ReturnDate = (DateTime)equipmentRecordDto.ReturnDate,
                        State = (int)equipmentRecordDto.State
                    };
                    i = await _equipmentRecordRepository.Add(newEquipmentRecord);
                    if (i <= 0)
                    {
                        res.Message = APIEnum.创建失败.ToString();
                        res.Data = 0;
                    }
                }
                else
                {
                    var newEquipmentRecord = new EquipmentRecord
                    {
                        Id = equipmentRecordDto.Id ?? 0, // 确保Id为非空
                        EquipmentType = equipmentRecordDto.EquipmentType,
                        EquipmentNo = equipmentRecordDto.EquipmentNo,
                        Borrower = equipmentRecordDto.Borrower,
                        borrowDate = equipmentRecordDto.BorrowDate,
                        CurrentUser = equipmentRecordDto.CurrentUser,
                        ReturnUser = equipmentRecordDto.ReturnUser,
                        ReturnDate = DateTime.Now,
                        State = (int)equipmentRecordDto.State
                    };
                    i = await _equipmentRecordRepository.Update(newEquipmentRecord);
                    if (i <= 0)
                    {
                        res.Message = APIEnum.更新失败.ToString();
                        res.Data = 0;
                    }
                    else
                    {
                        res.Message = APIEnum.更新成功.ToString();
                        res.Data = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                res.Message = string.Format("创建/更新设备借还记录失败：{0}", ex.Message);
                res.Data = false;
            }
            return res;
        }

        /// <summary>
        /// 获取设备借还记录列表（支持分页和搜索）
        /// </summary>
        /// <param name="equipmentRecordQueryAttribute">请求</param>
        /// <returns>返回数据</returns>
        public async Task<APIResult<PageGridData<EquipmentRecordDTO>>> GetEquipmentRecordList(EquipmentRecordQueryAttribute equipmentRecordQueryAttribute)
        {
            try
            {
                var query = _equipmentRecordRepository
                    .GetAll()
                    .AsNoTracking();

                if (!string.IsNullOrEmpty(equipmentRecordQueryAttribute.EquipmentType))
                {
                    query = query.Where(x => x.EquipmentType.Contains(equipmentRecordQueryAttribute.EquipmentType));
                }

                if (!string.IsNullOrEmpty(equipmentRecordQueryAttribute.EquipmentNo))
                {
                    query = query.Where(x => x.EquipmentNo.Contains(equipmentRecordQueryAttribute.EquipmentNo));
                }

                if (equipmentRecordQueryAttribute.State.HasValue)
                {
                    query = query.Where(x => x.State == equipmentRecordQueryAttribute.State.Value);
                }

                var totalCount = await query.CountAsync();
                //var list = await query
                //    .OrderByDescending(x => x.borrowDate)
                //    .Skip((equipmentRecordQueryAttribute.PageIndex - 1) * equipmentRecordQueryAttribute.PageSize)
                //    .Take(equipmentRecordQueryAttribute.PageSize)
                //    .ToListAsync();

                var result = new PageGridData<EquipmentRecordDTO>
                {
                    rows = query.Select(x => new EquipmentRecordDTO
                    {
                        Id = x.Id,
                        EquipmentType = x.EquipmentType,
                        EquipmentNo = x.EquipmentNo,
                        Borrower = x.Borrower,
                        BorrowDate = x.borrowDate,
                        CurrentUser = x.CurrentUser,
                        ReturnUser = x.ReturnUser,
                        ReturnDate = x.ReturnDate,
                        State = x.State
                    }).OrderByDescending(x => x.Id)
                    .Skip((equipmentRecordQueryAttribute.PageIndex - 1) * equipmentRecordQueryAttribute.PageSize)
                    .Take(equipmentRecordQueryAttribute.PageSize).ToList(),
                    total = totalCount,
                    status = (int)Math.Ceiling(equipmentRecordQueryAttribute.PageIndex * 1.0 / equipmentRecordQueryAttribute.PageSize)
                };

                return new APIResult<PageGridData<EquipmentRecordDTO>>
                {
                    Data = result,
                    Message = "获取成功",
                    Code = APIEnum.查询成功
                };
            }
            catch (Exception ex)
            {
                return new APIResult<PageGridData<EquipmentRecordDTO>>
                {
                    Message = $"获取失败: {ex.Message}",
                    Code = APIEnum.查询成功
                };
            }
        }
    }
}
